<?php
include "mysql_config.php";

set_time_limit(0);
date_default_timezone_set("Asia/Shanghai");
header("Content-Type: text/html; charset=UTF-8");
$mysqlConfig = new MysqlConfig();
$mysqli = new mysqli($mysqlConfig->getMysqlServerName(), $mysqlConfig->getMysqlUserName(), $mysqlConfig->getMysqlPassword(), $mysqlConfig->getMysqlDatabase());
//$thisMonthFirstDay = date('Y-m-01');
//$lastMonthLastTime = date('Y-m-d', strtotime($thisMonthFirstDay) - 86400) . " 23:59:59";
//$lastMonthFirstTime = date('Y-m-01', strtotime($thisMonthFirstDay) - 86400) . " 00:00:00";
//$thisMonthFirstDay = date('Y-m-01');
$lastMonthLastTime = date('Y-m-d H:i:s', time());
$lastMonthFirstTime = date('Y-m-d H:i:s', time() - 60*10);
$shopIds = [];
$supermarketOrderSql = "select id, shopid, cityid from 91fbw_orders where (supermarketcoupontype='free' or supermarketcoupontype='recharge') and created_at>='".$lastMonthFirstTime."' and created_at<='" .$lastMonthLastTime."';";
$supermarketOrderResult = $mysqli->query($supermarketOrderSql);
$orderLists = [];
while ($supermarketOrderRow = mysqli_fetch_assoc($supermarketOrderResult)) {
    $shopId = $supermarketOrderRow['shopid'];
    array_push($orderLists, [
            'id' => $supermarketOrderRow['id'],
            'shopid' => $shopId,
            'cityid' => $supermarketOrderRow['cityid']
        ]);
    if(!in_array($shopId, $shopIds)) {
        array_push($shopIds, $shopId);
    }
}
foreach ($shopIds as $shopId) {
    $orderIdString = '';
    $accountAmount = 0;
    $cityId = '';
    foreach($orderLists as $orderList) {
        if ($orderList['shopid'] != $shopId) {
            continue;
        }
        $accountAmount++;
        $orderIdString .= $orderList['id'] . ',';
        $cityId = $orderList['cityid'];
    }
    $orderIdString = rtrim($orderIdString, ',');
    $insertSupermarketSubsidySql = "insert into 91fbw_supermarket_subsidies (`cityid`,`shopid`,`type`,`orderid`,`accountamount`,`created_at`,`updated_at`)" .
        "  values(".$cityId.", ".$shopId.", 'oneyuan', '".$orderIdString."', ".$accountAmount.", '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."');";
    $mysqli->query($insertSupermarketSubsidySql);
}
$mysqli->close();